package com.agent;

import java.io.IOException;

import com.agent.coreservice.Application;
import com.agent.coreservice.TAEventHandler;
import com.agent.diagnostic.AbtTrace;

public class ReflectionMain {

	final static String CLASS_TRACE = "[JAVA AGENT]";
	static String FUNCTION_TRACE = "";
	Application comm;
	static String fileName = "C:\\Users\\Public\\Bridge\\BridgeInfo.txt";
	
	// Create the GUI
	private static ReflectionMain instance = null;
	
	public ReflectionMain(){
		instance = this;
		AbtTrace.info("######  Start Loading JavaAgent...");
		try {
			System.out.println("=== ReflectionMain ==========");
			initialize();
		} catch (Exception e) {
			AbtTrace.error(String.format("[%s][JavaAgent]Exception: %s", CLASS_TRACE, e.getMessage()));
		}
		
		AbtTrace.info("######  End Loading JavaAgent...");
	}
	
	public static ReflectionMain getInstance()
	{
		if(ReflectionMain.instance == null)
		{
			new ReflectionMain();
		}
		
		return ReflectionMain.instance;
	}
	
	/**
	 *   call extension which register event Java Agent initialize 
	 */
	private void onInitialize()
	{
		TAEventHandler.getInstance().initiallize();
	}
	
	/**
	 * initialize all data when Java Agent is loaded
	 * + open TCP/IP socket to listen message from Bridge
	 * + save information of TAC/IP socket to file Bridge.txt in folder "C:\Users\Public\Bridge"
	 * with format: [hwnd]=>[port]
	 * @throws IOException
	 */
	public void initialize() throws IOException{
		//open TCP/IP socket to listen message from Bridge
		comm = Application.getInstance();
		comm.initListenerPort();
		final int port = comm.getListenerPort();
		System.out.println(" ============= Get port success  ====== port: " + port);
		
		System.out.println(" ============= handle event ============");
		// handle event initialize
		this.onInitialize();
		
//		try{
//			Thread t = new Thread() {
//				public void run() {	
//					System.out.println(" ============= Start listener success  ====== port: " + port);
//					comm.startListener(port);
//					System.out.println("ok con de!!!!!");
//					
//				}
//			};
//			//t.setDaemon(true);
//			t.start();
//		}
//		catch(Exception e)
//		{
//			AbtTrace.error(String.format("[%s][%s] Exception: %s", CLASS_TRACE, FUNCTION_TRACE, e.getMessage()));
//		}
		
		//start listener
//		Runnable runnable = new Runnable() {
//			@Override
//			public void run() {
//				comm.startListener(port);
//				System.out.println(" ============= Start listener success  ====== port: " + port);
//			}
//		};
//		runnable.run();
		
	}
	
}
